package com.young.springboot.kafka;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.kafka.annotation.KafkaHandler;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.messaging.handler.annotation.Payload;

import java.util.Iterator;
import java.util.List;

/**
 * @description：
 * @author: yangyahui01
 * @date: 12/5/24 3:02 PM
 */
public abstract class CommonBatchMessageListener<V> implements InitializingBean {

    private RecordFilter<V> filter;

    @Override
    public void afterPropertiesSet() throws Exception {
        filter = buildFilter();
    }

    @KafkaHandler
    public void onMessage(@Payload List<V> records, Acknowledgment acknowledgment) {
        try {
            filter(records);
            if (!records.isEmpty()) {
                process(records);
            }
            acknowledgment.acknowledge();
        } catch (Exception e) {
            throw new RuntimeException("kafka message process error!",e);
        }
    }

    protected void filter(List<V> records) {
        if (filter == null) {
            return;
        }
        Iterator<V> iterator = records.iterator();
        while (iterator.hasNext()) {
            if (filter.filter(iterator.next())) {
                iterator.remove();
            }
        }
    }

    public abstract void process(List<V> record);

    /**
     * 只调用一次,构建自己的过滤器
     * @return
     */
    public abstract RecordFilter<V> buildFilter();
}
